package com.hedgehoglab.fixxclipse.treeviewer.ui;

import java.util.Iterator;
import java.util.List;

import java.util.Properties;


import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.hedgehoglab.fixxclipse.services.ProjectService;
import com.hedgehoglab.fixxclipse.treeviewer.model.Fixx;
import com.hedgehoglab.fixxclipse.treeviewer.model.Project;




public class FixxView extends ViewPart {
	protected TreeViewer treeViewer;
	protected Text text;
	protected FixxLabelProvider labelProvider;
	
	protected Action assignedToMeAction;
	protected Action criticalityAction, versionAction;
	protected Action addIssueAction, resolveAction;
	protected ViewerFilter assignedToMeFilter;
	protected ViewerSorter criticalitySorter, versionSorter;
	
	protected Fixx root;
	
	protected ProjectService projectsService = new ProjectService();
	
	public FixxView() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void createPartControl(Composite parent) {
		GridLayout layout = new GridLayout();
		layout.numColumns = 1;
		layout.verticalSpacing = 2;
		layout.marginWidth = 0;
		layout.marginHeight = 2;
		parent.setLayout(layout);
		
		/* Create a "label" to display information in. I'm
		 * using a text field instead of a lable so you can
		 * copy-paste out of it. */
		text = new Text(parent, SWT.READ_ONLY | SWT.SINGLE | SWT.BORDER);
		// layout the text field above the treeviewer
		GridData layoutData = new GridData();
		layoutData.grabExcessHorizontalSpace = true;
		layoutData.horizontalAlignment = GridData.FILL;
		text.setLayoutData(layoutData);
		
		treeViewer = new TreeViewer(parent);
		treeViewer.setContentProvider(new FixxContentProvider());
		labelProvider = new FixxLabelProvider();
		treeViewer.setLabelProvider(labelProvider);
		
		treeViewer.setUseHashlookup(true);
		
		// layout the tree viewer below the text field
		layoutData = new GridData();
		layoutData.grabExcessHorizontalSpace = true;
		layoutData.grabExcessVerticalSpace = true;
		layoutData.horizontalAlignment = GridData.FILL;
		layoutData.verticalAlignment = GridData.FILL;
		treeViewer.getControl().setLayoutData(layoutData);
		
		// Create menu, toolbars, filters, sorters.
		createFiltersAndSorters();
		createActions();
		createMenus();
		createToolbar();
		hookListeners();
		
		treeViewer.setInput(getInitalInput());
		treeViewer.expandAll();
	}
	
	protected void createFiltersAndSorters() {
		assignedToMeFilter = new AssignedToMeFilter();
		criticalitySorter = new CriticalitySorter();
		versionSorter = new VersionSorter();
	}
	
	protected void hookListeners() {
		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				// if the selection is empty clear the label
				if(event.getSelection().isEmpty()) {
					text.setText("");
					return;
				}
				if(event.getSelection() instanceof IStructuredSelection) {
					IStructuredSelection selection = (IStructuredSelection)event.getSelection();
					StringBuffer toShow = new StringBuffer();
					Iterator iterator2 = selection.iterator();
					for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
						Class d = iterator.next().getClass();
						Object b = d.cast(iterator2.next());
						String value = labelProvider.getText(b);
						toShow.append(value);
						toShow.append(", ");
					}
					// remove the trailing comma space pair
					if(toShow.length() > 0) {
						toShow.setLength(toShow.length() - 2);
					}
					text.setText(toShow.toString());
				}
			}
		});
	}
	
	protected void createActions() {
		criticalityAction = new Action("By Criticality") {
			public void run() {
				updateFilter(criticalityAction);
			}
		};
		criticalityAction.setChecked(false);
		
		assignedToMeAction = new Action("Assigned To Me") {
			public void run() {
				updateSorter(assignedToMeAction);
			}
		};
		assignedToMeAction.setChecked(false);
		
		versionAction = new Action("By Version") {
			public void run() {
				updateSorter(versionAction);
			}
		};
		versionAction.setChecked(false);
		
		addIssueAction = new Action("Add Issue") {
			public void run() {
				addNewIssue();
			}			
		};
		addIssueAction.setToolTipText("Add a New Issue");
//		addIssueAction.setImageDescriptor(TreeViewerPlugin.getImageDescriptor("newBook.gif"));

		resolveAction = new Action("Resolve") {
			public void run() {
				resolveSelected();
			}			
		};
		resolveAction.setToolTipText("Delete");
//		resolveAction.setImageDescriptor(TreeViewerPlugin.getImageDescriptor("remove.gif"));		
	}
	
	
	protected void addNewIssue() {
		//TODO DO
	}


	protected void resolveSelected() {
		//TODO DO
	}
	
	protected void createMenus() {
		IMenuManager rootMenuManager = getViewSite().getActionBars().getMenuManager();
		rootMenuManager.setRemoveAllWhenShown(true);
		rootMenuManager.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager mgr) {
				fillMenu(mgr);
			}
		});
		fillMenu(rootMenuManager);
	}


	protected void fillMenu(IMenuManager rootMenuManager) {
		IMenuManager filterSubmenu = new MenuManager("Filters");
		rootMenuManager.add(filterSubmenu);
		filterSubmenu.add(assignedToMeAction);
		
		IMenuManager sortSubmenu = new MenuManager("Sort By");
		rootMenuManager.add(sortSubmenu);
		sortSubmenu.add(criticalityAction);
		sortSubmenu.add(versionAction);
	}
	
	protected void updateSorter(Action action) {
		if(action == criticalityAction) {
			versionAction.setChecked(!criticalityAction.isChecked());
			if(action.isChecked()) {
				treeViewer.setSorter(criticalitySorter);
			} else {
				treeViewer.setSorter(null);
			}
		} else if(action == versionAction) {
			criticalityAction.setChecked(!versionAction.isChecked());
			if(action.isChecked()) {
				treeViewer.setSorter(versionSorter);
			} else {
				treeViewer.setSorter(null);
			}
		}
			
	}
	
	protected void updateFilter(Action action) {
		if(action == assignedToMeAction) {
			if(action.isChecked()) {
				treeViewer.addFilter(assignedToMeFilter);
			} else {
				treeViewer.removeFilter(assignedToMeFilter);
			}
		}
	}
	
	protected void createToolbar() {
		IToolBarManager toolbarManager = getViewSite().getActionBars().getToolBarManager();
		toolbarManager.add(resolveAction);
		toolbarManager.add(addIssueAction);
	}
	
	public Fixx getInitalInput() {
		root = new Fixx("Hedgehog Lab");
//		List<Project> projects = new ArrayList<Project>();
//		projects.add(new Project("fixx",root));
//		projects.add(new Project("solomon",root));
//		root.setProjects(projects);
//		List<Project> response = projectsService.getProjects();
//		System.out.println(response);	

		List<Project> response1 = projectsService.getProject("1",root);
		root.setProjects(response1);
		return root;
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

}
